package com.itheima.d03_threadpool_executors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 目标：了解线程池创建方式二
 *      使用线程池工具类Executors创建线程池
 */
public class Test {

    public static void main(String[] args) {
        //1.创建线程池对象
        //缺点1：可读性差
        //缺点2：任务队列无限制，可能存在内存溢出的风险
        ExecutorService pool1 = Executors.newFixedThreadPool(2); //底层使用是实现类：ThreadPoolExecutor

        //2.执行任务
        pool1.execute(()->{
            for (int i = 0; i < 10; i++) {
                System.out.println("HelloWorld" + i);
            }
        });

        pool1.execute(()->{
            for (int i = 0; i < 10; i++) {
                System.out.println("\t\tHelloWorld" + i);
            }
        });

        System.out.println("======================");

        //1.创建线程池对象
        //优点：具备延迟执行任务的效果
        ScheduledExecutorService pool2 = Executors.newScheduledThreadPool(2);

        //2.延迟执行任务：不和主线程竞争
        pool2.schedule(()->{
            int sum = 0;
            for (int i = 0; i < 10; i++) {
                sum += i;
                System.out.println("累加："+i);
            }
            System.out.println(sum);
        },10, TimeUnit.SECONDS);



    }
}
